<?php


	namespace app\services;


	use app\model\Setting;
	use think\cache\driver\Redis;
	use think\facade\Cache;

	class RedisServices
	{

		public $redis = null;

		public $setting_redis;


		public function __construct () {
			$this->redis = Cache::store('redis');

			$this->redis = new Redis(['password' => '123456']);
		}

		public function index ($request) {


			$username = $this->redis->get('usename');

			if (!$username) {

			}

			return $username;
		}


		public function setting () {

			$this->setting_redis = 'setting';
			$this->setnx_setting_redis = 'setnx_setting';

			$ret = $this->redis->get("setting");

			if (!$ret) {
				//加排斥锁防止击穿
				//现在有1000个请求同时进来,让一个来查询数据库并且缓存到缓存系统中
				//其他的等待一下去缓存系统中去拿
				if ($this->redis->setnx($this->setnx_setting_redis, 1, 30)) {
					//从数据库中获取
					$ret = Setting::order('id desc')->find();
					if (!$ret) {//防止穿透
						$ret = null;
					}

					//加入到缓存系统中
					$this->redis->set($this->setting_redis, $ret);
					//删除互斥锁
					$this->redis->del($this->setnx_setting_redis);
				} else {
					//未抢到锁的,直接获取
					$this->setting();
				}
			}

			return $ret;
		}


		/**
		 * 穿透：缓存系统和数据库中都没有数据,将查询的结果置空
		 * 击穿：缓存系统中的数据过期的一瞬间,去数据库中查询结果
		 */

	}
